package homework.util;

import homework.bean.ClassBean;
import homework.bean.StudentBean;

import java.io.*;
import java.sql.*;
import java.util.*;

/**
 * @Author(作者) ys
 * @Description(类的描述):  提供数据的工具类
 * @Date(创建时间)
 * @version(开发的版本):1.0
 **/
public class DataUtil {
    /**
     * 存储学生对象的集合
     */
    public  static  Map<Integer, StudentBean> studentsInfo = new HashMap<Integer, StudentBean>();
    /**
     * 存储班级的集合
     */
    public static  Map<Integer, ClassBean> classesInfo=new HashMap<Integer, ClassBean>();

    //记录下一个学生的编号
    public static int nextId;

    static{
        Connection c = null;
        ResultSet rSet = null;
        Statement s = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            c = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/j180?useSSL=false&serverTimezone=Asia/Shanghai",
                    "root",
                    "root"
            );

            String stSql = "select * from stuinfo";
            String clSql = "select * from clainfo";

            s = c.createStatement();

            rSet = s.executeQuery(clSql);
            while(rSet.next()){
                ClassBean cla = new ClassBean();
                cla.setClassId(rSet.getInt("cid"));
                cla.setName(rSet.getString("cname"));
                classesInfo.put(cla.getClassId(), cla);
            }

           rSet = s.executeQuery(stSql);
           while(rSet.next()){
               StudentBean studentBean = new StudentBean();
               studentBean.setStudentId(rSet.getInt("sid"));
               studentBean.setName(rSet.getString("sname"));
               studentBean.setGender(rSet.getString("sgender"));
               studentBean.setAge(rSet.getInt("sage"));
               studentBean.setPicture("E:\\javaooGit\\jdbc_01\\src\\homework\\data" +File.separator
                       + rSet.getString("picPath"));
               studentBean.setClassBean(getClassById(rSet.getInt("cid")));
               studentsInfo.put(studentBean.getStudentId(), studentBean);
           }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(c != null){
                try {
                    c.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(s != null){
                try {
                    s.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(rSet != null){
                try {
                    rSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        nextId = studentsInfo.size() + 1;
    }

    private DataUtil(){

    }

    /**
     * 查询所有的学生
     * @return  list类型的学生集合的对象
     */
    public static List<StudentBean> getAllStudents(){
        //创建用来保存学生对象的集合
        List<StudentBean> list = new ArrayList<StudentBean>();
        //从 学生的map集合中遍历所有的学生对象 并把每个学生保存到list集合中
          Set<Integer> keys =    studentsInfo.keySet();
        for (Integer key : keys) {
            StudentBean studentBean = studentsInfo.get(key);
            list.add(studentBean);
        }
        return list;
    }
    /**
     * 查询所有的班级
     * @return  班级对象的集合
     */
    public static List<ClassBean> getAllClasses(){
        //创建用来保存学生对象的集合
        List<ClassBean> list = new ArrayList<ClassBean>();
        //从 学生的map集合中遍历所有的学生对象 并把每个学生保存到list集合中
        Set<Integer> keys =    classesInfo.keySet();
        for (Integer key : keys) {
            ClassBean classBean = classesInfo.get(key);
            list.add(classBean);
        }
        return list;
    }

    /**
     *
     * @param studentBean 学生对象
     */
    public static void  addStudent(StudentBean studentBean){
        studentsInfo.put(studentBean.getStudentId(),studentBean);
        //记录下一个学生的编号
         nextId++;
    }

    /**
     * 删除
     * @param studentId
     */
    public static void  deleteStudent(Integer studentId){

        studentsInfo.remove(studentId);
    }

    /**
     * 修改
     * @param studentBean
     */
    public static  void  updateStudent(StudentBean studentBean){

        studentsInfo.put(studentBean.getStudentId(),studentBean);
    }
    /**
     * 根据编号来查询学生
     * @param studentId 学生编号
     * @return  该编号的学生对象
     */
    public static StudentBean getStudentById(Integer studentId){

        StudentBean studentBean = studentsInfo.get(studentId);

        return studentBean;
    }

    public static ClassBean getClassById(int id){
        return classesInfo.get(id);
    }

    public static int getIdByClass(ClassBean classBean){
        int classId = -1;
        Set<Integer> classIds = classesInfo.keySet();

        for (Integer id : classIds) {
            if(classesInfo.get(id) == classBean){
                classId = id;
                break;
            }
        }

        return classId;
    }
    /**
     * 将学生和班级对象序列化到文件中
     */
    public static void serializableStudentAndClass(){
     //   deletePic();
        Connection c = null;
        ResultSet rSet = null;
        Statement s = null;

        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            c = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/j180?useSSL=false&serverTimezone=Asia/Shanghai",
                    "root",
                    "root"
            );

            String sql = null;
            s = c.createStatement();
             s.executeUpdate("truncate  stuinfo");
             s.executeUpdate("truncate clainfo");

             List<ClassBean> cList = getAllClasses();
            for (ClassBean classBean : cList) {
                s.executeUpdate("insert into clainfo values(null,'"+classBean.getName()+"')");
            }

            List<StudentBean> sList = getAllStudents();
            for (StudentBean studentBean : sList) {
                studentBean.setPicture(savePicture(studentBean.getPicture()));
                s.executeUpdate("insert into stuinfo values(null,'"
                        +studentBean.getName()+"','"
                        +studentBean.getGender()+"',"
                        +studentBean.getAge()+",'"
                        +studentBean.getPicture()+"', "
                        +getIdByClass(studentBean.getClassBean())+");");
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(c != null){
                try {
                    c.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(s != null){
                try {
                    s.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(rSet != null){
                try {
                    rSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 保存用户上传的照片
     * @param filePath 上传照片的路径
     * @return 保存照片的路径
     */
    public static String  savePicture(String filePath){

        File file = new File(filePath);
        String rPath = System.currentTimeMillis()
                + filePath.substring(filePath.lastIndexOf("."));
        String path = "E:\\javaooGit\\jdbc_01\\src\\homework\\data"+
                File.separator + rPath;
        File picFile = new File(path);

        try(
                InputStream in = new FileInputStream(file);
                OutputStream out = new FileOutputStream(picFile);
                ){
            int a = 0;
            while(a != -1){
                a = in.read();
                out.write((char)a);
            }
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(rPath);
        return rPath;
    }

    public static void deletePic(){
        File f = new File("E:\\javaooGit\\jdbc_01\\src\\homework\\data");
        if(f.isDirectory()){
            File[] fs = f.listFiles();
            for (File file : fs) {
                file.delete();
            }
        }
    }
}